package com.blockmeta.bbs.overallserviceapplication.activity.login;

import android.content.Context;
import android.content.Intent;

import com.blankj.utilcode.util.LogUtils;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.SimpleTextWatcher;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.security.AESPKCS7Util;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.business.UmengEvent;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.blockmeta.bbs.businesslibrary.net.retrofit.RetrofitFactory;
import com.blockmeta.bbs.businesslibrary.net.rxjava.CommonSubscriber;
import com.blockmeta.bbs.businesslibrary.net.rxjava.RxUtil;
import com.blockmeta.bbs.businesslibrary.pojo.LoginPOJO;
import com.blockmeta.bbs.businesslibrary.pojo.UserPhonePOJO;
import com.blockmeta.bbs.businesslibrary.popwindow.UserAgreementPopupWindow;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.AppCode;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.net.api.NetApi;

import com.blockmeta.bbs.overallserviceapplication.umeng.ThirdLoginDataPOJO;
import com.blockmeta.bbs.overallserviceapplication.umeng.UMLoginListener;
import com.blockmeta.bbs.overallserviceapplication.web.WebActivity;
import com.google.gson.Gson;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import okhttp3.RequestBody;

/**
 * Created by author on 2017/12/27.
 * 用户名密码登陆
 */
@Route(path = RouterPath.ACCOUNT_LOGIN_ACTIVITY)
public class LoginAccountActivity extends BaseActivity implements View.OnClickListener {
    private Context mContext;
    private View v;
    private LinearLayout finish;
    private EditText username;
    private EditText pwd;
    private Button forget;
    private TextView back;
    private TextView register;
    private ArrayList<TextView> tvs;
    private Button login;
    private HashMap<String, String> loginMap;
    private RelativeLayout loginSina, loginWechat, loginQQ;
    private UMShareAPI mUMShareAPI;
    //登陆平台 weixin,qq,weibo
    private String type;
    //友盟回调监听
    private UMLoginListener mUMLoginListener;
    //用户协议选项
    private CheckBox mUserProtocolBox;

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        mContext = LoginAccountActivity.this;

        v = LayoutInflater.from(mContext).inflate(R.layout.activity_login_account, null);
        initData();

        return v;
    }

    private void initData() {
        finish = (LinearLayout) v.findViewById(R.id.login_account_finish);
        username = (EditText) v.findViewById(R.id.login_account_username);
        pwd = (EditText) v.findViewById(R.id.login_account_pwd);
        forget = (Button) v.findViewById(R.id.login_account_forget);
        back = (TextView) v.findViewById(R.id.login_account_back);
        register = (TextView) v.findViewById(R.id.register_account);
        login = (Button) v.findViewById(R.id.btn_login);
        loginSina = (RelativeLayout) v.findViewById(R.id.rl_login_sina);
        loginWechat = (RelativeLayout) v.findViewById(R.id.rl_login_wechat);
        loginQQ = (RelativeLayout) v.findViewById(R.id.rl_login_qq);
        mUserProtocolBox = v.findViewById(R.id.box);
        mUMShareAPI = UMShareAPI.get(this);

        finish.setOnClickListener(this);
        back.setOnClickListener(this);
        forget.setOnClickListener(this);
        loginSina.setOnClickListener(this);
        loginWechat.setOnClickListener(this);
        loginQQ.setOnClickListener(this);
        register.setOnClickListener(this);
        v.findViewById(R.id.box_desc2).setOnClickListener(this);

        inputCheck();
        initUmengListener();
    }

    private void inputCheck() {
        tvs = new ArrayList<>();
        tvs.add(username);
        tvs.add(pwd);
        SimpleTextWatcher textWatcher = new SimpleTextWatcher(tvs);
        textWatcher.setNoEmpty(new SimpleTextWatcher.TvCallBack() {
            @Override
            public void withEmpty() {
            }

            @Override
            public void noEmpty() {
                login.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (hasAgreedProtocol()) {
                            login();
                        }
                    }
                });
            }
        });
        username.addTextChangedListener(textWatcher);
        pwd.addTextChangedListener(textWatcher);
    }

    private boolean hasAgreedProtocol() {
        boolean hasAgreed = mUserProtocolBox.isChecked();
        if (!hasAgreed) {
            ToastUtil.show("您尚未同意用户协议");
        }
        return hasAgreed;
    }

    private void login() {
        if (loginMap == null) {
            loginMap = new HashMap<>(8);
        }
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);
        loginMap.put("username", username.getText().toString());
        loginMap.put("password", AESPKCS7Util.encrypt(pwd.getText().toString(), "tomSun28HaHaHaHa"));
        loginMap.put("source", "app");
        loginMap.put("device_id", DeviceUtil.getIMEI());
        loginMap.put("product_code", myAppCode);

        RetrofitFactory.getRootRetrofit().create(NetApi.AccountLogin.class)
                .accountLogin(RequestBody.create(NetApi.sMediaType, new Gson().toJson(loginMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .compose(RxUtil.<LoginPOJO>commonResultByCode())
                .subscribe(new CommonSubscriber<LoginPOJO>(mContext) {
                    @Override
                    public void onNext(LoginPOJO loginPOJO) {
                        saveUserInfo(loginPOJO);
                        finish();
                    }
                });
    }

    private void saveUserInfo(LoginPOJO loginPOJO) {
        if (loginPOJO.userInfo == null) {
            return;
        }
        UserPhonePOJO userPhonePOJO = new UserPhonePOJO();
        userPhonePOJO.setLogo(loginPOJO.userInfo.logo);
        userPhonePOJO.setEmail(loginPOJO.userInfo.email);
        userPhonePOJO.setMobile(loginPOJO.userInfo.mobile);
        userPhonePOJO.setUid(loginPOJO.userInfo.uid);
        LogUtils.d("author saveUserInfo" + loginPOJO.userInfo.uid);
        userPhonePOJO.setUserName(loginPOJO.userInfo.userName);
        userPhonePOJO.setNickName(loginPOJO.userInfo.nickName);
        userPhonePOJO.setToken(loginPOJO.token);

        AccountHelper.doLogin(userPhonePOJO);

    }


    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.login_account_finish) {
            finish();
//            ThrioNavigator.pop(null, false);
        } else if (i == R.id.login_account_back) {

            activityStartActivity(mContext, LoginPhoneActivity.class);
//            ThrioNavigator.push("/native/LoginPhoneActivity",
//                "test",
//                false,
//                (v) -> {
//                    return null;
//                }
//        );
//            ThrioNavigator.pop(null, false);
            finish();

        } else if (i == R.id.register_account) {
//            ThrioNavigator.push("/native/RegisterAccountActivity",
//                    "test",
//                    false,
//                    (v) -> {
//                        return null;
//                    }
//            );
            activityStartActivity(mContext, RegisterAccountActivity.class);
        } else if (i == R.id.login_account_forget) {
            ToastUtil.show(mContext, "忘记了密码");

        } else if (i == R.id.rl_login_sina) {
            if (!hasAgreedProtocol()) {
                return;
            }
            type = "weibo";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.SINA, mUMLoginListener);

        } else if (i == R.id.rl_login_wechat) {
            if (!hasAgreedProtocol()) {
                return;
            }
            type = "weixin";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.WEIXIN, mUMLoginListener);

        } else if (i == R.id.rl_login_qq) {
            if (!hasAgreedProtocol()) {
                return;
            }
            type = "qq";
            mUMShareAPI.getPlatformInfo(this, SHARE_MEDIA.QQ, mUMLoginListener);
        } else if (i == R.id.box_desc2) {
            UserAgreementPopupWindow popupWindow = new UserAgreementPopupWindow(mContext, 1);
            popupWindow.setOnPositive(new UserAgreementPopupWindow.OnPositive() {
                @Override
                public void onPositive() {
                }
            });
            popupWindow.showPopupWindow();

//            Intent intent = new Intent(mContext, WebActivity.class);
//            intent.putExtra(Constant.ZERO, mContext.getResources().getString(R.string.user_login_protocol_url));
//            intent.putExtra(Constant.ONE, mContext.getResources().getString(R.string.user_login_protocol));
//            startActivity(intent);
        }
    }


    /**
     * 三方登陆成功的回调信息
     */
    private void initUmengListener() {
        mUMLoginListener = new UMLoginListener(mContext) {
            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                for (Map.Entry<String, String> stringEntry : map.entrySet()) {
                    Log.d("airthor", stringEntry.getKey() + ":" + stringEntry.getValue());
                }
                String stoken = map.get("accessToken");
                String openId = map.get("openid") == null ? map.get("uid") : map.get("openid");
                String unionId = map.get("unionid");
                String nickName = map.get("name");
                String avatar = map.get("avatar_large");
                if (TextUtils.isEmpty(avatar)) {
                    avatar = map.get("iconurl");
                }

                ThirdLoginDataPOJO.getINSTANCE().setUid(openId);
                ThirdLoginDataPOJO.getINSTANCE().setUnionid(unionId);
                ThirdLoginDataPOJO.getINSTANCE().setName(nickName);
                ThirdLoginDataPOJO.getINSTANCE().setIconUrl(avatar);
                ThirdLoginDataPOJO.getINSTANCE().setType(type);
                ThirdLoginDataPOJO.getINSTANCE().setStoken(stoken);
                checkTripartiteLogin(openId, unionId, nickName, avatar, type, stoken);

                HashMap<String, String> map1 = new HashMap<>();
                map1.put("type", share_media == null ? "" : share_media.toString());
                UmengEvent.eventStatistics(mContext, Constant.U_LOGIN, map1);
            }
        };
    }

    /**
     * 验证三方登陆的信息，判断是否需要绑定
     *
     * @param openId   三方登陆的唯一标识
     * @param nickName 昵称
     * @param avatar   头像链接
     * @param type     使用哪个三方平台登陆的 weixin qq weibo
     */
    private void checkTripartiteLogin(String openId, String unionid, String nickName, String avatar, String type, String stoken) {
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
        String myAppCode = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id);
        HashMap<String, String> checkMap = new HashMap<>();
        checkMap.put("openid", openId);
        checkMap.put("unionid", unionid);
        checkMap.put("nickname", nickName);
        checkMap.put("avatar", avatar);
        checkMap.put("type", type);
        checkMap.put("stoken", stoken);
        checkMap.put("device_id", DeviceUtil.getIMEI());
        checkMap.put("product_code", myAppCode);
        checkMap.put("source", "app");

        RetrofitFactory.getRootRetrofit().create(NetApi.SocialLogin.class)
                .socialLogin(RequestBody.create(NetApi.sMediaType, new Gson().toJson(checkMap)))
                .compose(this.<BaseCodeResponse<LoginPOJO>>bindToLifecycle())
                .compose(RxUtil.<BaseCodeResponse<LoginPOJO>>rxSchedulerHelper())
                .subscribe(new CommonSubscriber<BaseCodeResponse<LoginPOJO>>(mContext) {
                    @Override
                    public void onNext(BaseCodeResponse<LoginPOJO> response) {
                        if (response.code.equals(20080001)) {//服务器返回对象不存在
                            startActivity(new Intent(LoginAccountActivity.this, BindAccountActivity.class));
                            finish();
                        } else if(response.data != null){
                            saveUserInfo(response.data);
                            finish();
                        }else {//登录失败
                            ToastUtil.show(response.msg);
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mUMShareAPI.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUMShareAPI.release();
    }
}
